package com.yztc.ui.Tuijian.fragment;


import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshGridView;
import com.yztc.bean.Constans;
import com.yztc.bean.YxlmBean;
import com.yztc.qmtv.R;
import com.yztc.ui.Tuijian.adapter.QuanBuAdapter;
import com.yztc.ui.bofang.BoFangActivity;
import com.yztc.utils.HttpHelper;
import com.yztc.utils.HttpUtils;
import com.yztc.utils.JsonUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class QuanBuFragment extends Fragment implements AdapterView.OnItemClickListener{


    private PullToRefreshGridView mPullGridView;
    private GridView gridView;
    private QuanBuAdapter adapter;
    private List<YxlmBean.DataBean> data;
    private Activity mActivity;
    private RelativeLayout mRelativeLayout;
    private ImageView imageView;
    private AnimationDrawable animationDrawable;

    public QuanBuFragment() {

    }
    private final int NULL=0;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case Constans.OK:
                    data = (List<YxlmBean.DataBean>) msg.obj;
                    adapter = new QuanBuAdapter(getActivity(), data);
                    gridView.setAdapter(adapter);
                    imageView.setVisibility(View.GONE);
                    mPullGridView.setVisibility(View.VISIBLE);
                    break;
                case Constans.ERRO:
                    break;
                case Constans.NULL:
                    break;
            }
        }
    };

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mActivity = activity;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_quan_bu2, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //关联
        mPullGridView = (PullToRefreshGridView) view.findViewById(R.id.quanbu_pull_refresh_grid);
        //设置刷新模式
        mPullGridView.setMode(PullToRefreshBase.Mode.BOTH);
        gridView = mPullGridView.getRefreshableView();
        dongHua(view);
        //隐藏
        mPullGridView.setVisibility(View.GONE);
        //设置刷新监听
        mPullGridView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<GridView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<GridView> refreshView) {
                data.clear();
//              刷新后再次下载
                getHttpResult();
                //
                adapter.notifyDataSetChanged();
                imageView.setVisibility(View.VISIBLE);
                mPullGridView.setVisibility(View.VISIBLE);
                mPullGridView.onRefreshComplete();

            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<GridView> refreshView) {

                adapter.notifyDataSetChanged();
                mPullGridView.setVisibility(View.VISIBLE);
                mPullGridView.onRefreshComplete();

            }
        });

       //设置监听
       gridView.setOnItemClickListener(this);

        //下载数据
        getHttpResult();
        if(animationDrawable!=null&&animationDrawable.isRunning()){
            animationDrawable.stop();
        }
    }
    //下载展示数据
    public void getHttpResult(){
        final String url = getArguments().getString("url");
        new Thread(new Runnable() {
          @Override
          public void run() {
              Message msg = Message.obtain();
              if(HttpHelper.isNetworkConnected(getActivity())){

                  if(!TextUtils.isEmpty(url)){
                      try {
                          byte[] result = HttpUtils.getHttpUtils().getJson(url);
                          //解析
                          List<YxlmBean.DataBean> data = JsonUtils.froJsonToList(new String(result, 0, result.length));
                          if(data.size()!=0&& data!=null){
                              msg.what = Constans.OK;
                              msg.obj = data;
                          }else {
                              msg.what = Constans.NULL;
                          }
                          Log.i("tag","----data.size()--------------------"+data.size());
                      } catch (IOException e) {
                          e.printStackTrace();
                      }
                  }else {
                      Log.i("tag","网址为空");
                  }
              }else {
                  Log.i("tag","网络异常");
                  msg.what = Constans.ERRO;
              }

              handler.sendMessageDelayed(msg,4000);
          }
      }).start();

    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        String uid = data.get(i).getUid();
        Intent intent = new Intent(mActivity,BoFangActivity.class);
        intent.putExtra("uid",uid);
        startActivity(intent);

    }

    //加载动画
    void dongHua(View view){
        mRelativeLayout = (RelativeLayout) view.findViewById(R.id.quanbu_fragment_layout);
        imageView = (ImageView) view.findViewById(R.id.imageView);
        imageView.setImageResource(R.drawable.loading_anim);
        animationDrawable = (AnimationDrawable) imageView.getDrawable();
        animationDrawable.start();
    }
}
